<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2018/6/16
 * Time: 21:00
 */
namespace Pay\Controller;

use Common\Common\Api\Order;
use Common\Common\Api\Ordermember;
use Common\Common\Api\Redis\Channel;
use Common\Common\Api\Redis\Product;

/**
 * Class ManyiController
 * @package Pay\Controller
 * 新中天4 ajie
 */
class Xinzt4Controller extends PayController{
    protected $config;
    protected $class;
    public function __construct(){
        parent::__construct();
        $classes = explode("\\",__CLASS__);
        $class = end($classes);
        $this->class = substr($class, 0, stripos($class, "Controller"));
    }

    public function pay($array){
        $this->config = Channel::getInstance()->getById($array['channel']);

        if(!$this->config){
            $this->showmessage('通道错误!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $parameter = array(
            'code' => $this->config['code'], // 通道名称
            'title' => $this->config['title'],
            'exchange' => 1, // 金额比例
            'gateway' => $this->config['gateway'],
            'orderid' => createOrderId(),
            'out_trade_id' => I("request.ordNo") ? I("request.ordNo") : I("request.pay_orderid"),
            'body' => 'pay',
            'channel'=>$array
        );

        // $isMobile = isMobile();
        $return = $this->orderadd( $parameter );

        switch($this->config['paytype']){

            //支付宝
            case 3:
            case 17: //原生
            case 4:
            case 18: //原生
                $pay_bankcode = 'ALIPAYJSAPI';
                break;
            //支付宝H5
            case 4:
            case 18: //原生
                $pay_bankcode = 'ALIPAYJSAPI';
                break;
            default:
                $this->showmessage('暂不支持此方式!',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $dataArr    = array(
            'apiCode'           => 'YL-PAY',
            'inputCharset'      => 'UTF-8',
            'signType'          => 'MD5',
            'partner'           => $this->config['mch_id'],
            'outOrderId'        => $return['orderid'],
            'product'           => 'wlf',
            'amount'            => intval($return['amount']),
            'extParam'          => '',
            'returnParam'       => '',
            'interfaceCode'     => '',
            'payType'           => $pay_bankcode,
            'authCode'          => '',
            'bankCardNo'        => '',
            'notifyUrl'         => $return['notifyurl'],
        );

        $sign = $this->sign($dataArr);

        $dataArr['sign']    = $sign;


        $res = curl($this->config['gateway'], httpstr($dataArr));


        /*string(671) "{"sign":"8EEB0440E48DEAD205E57E09F82589F8","apiCode":"YL-PAY","responseCode":"0000","inputCharset":"UTF-8","qrCodeImgUrl":"https://api.zk1006.cn/qrCode?s=https://qr.alipay.com/_d?_b=peerpay&enableWK=YES&biz_no=2019073004200330001041662737_90c37dccb3b50c3a8d95ba67ef27b7d9&app_name=tb&sc=qr_code&v=20190806&sign=51facc&__webview_options__=pd%3dNO","orderCode":"TO-20190731-101099899350","qrCodeUrl":"https://qr.alipay.com/_d?_b=peerpay&enableWK=YES&biz_no=2019073004200330001041662737_90c37dccb3b50c3a8d95ba67ef27b7d9&app_name=tb&sc=qr_code&v=20190806&sign=51facc&__webview_options__=pd%3dNO","partner":"C100629","responseMsg":"SUCCESS","outOrderId":"sn20190731121207998"}"
         * */
        $resp = json_decode($res,true);

       // var_dump('<pre/>',$sign,$dataArr,$this->config['gateway'],$this->config['signkey'],$res);exit();


        $code = $resp['qrCodeUrl'];
        $code1 = $resp['qrCodeImgUrl'];

        if(!$code){
            if($resp['responseMsg']){
                $this->showmessage($resp['responseMsg'],['code'=>C("THIRDCODES.".$this->class)]);
            }

            $this->showmessage('获取支付连接失败！',['code'=>C("THIRDCODES.".$this->class)]);
        }

        $paytype = transArr( C("PAYTYPES"), "id");
        $this->assign("wap_url", $code);
        $this->assign("code_url", $code1);
        $this->assign("title", $paytype[$this->config['paytype']]);
        $this->assign("return", $return);
       // $this->assign("imgurl", C("website.DOMAIN")."/Pay_Qrcode_getCode?type=2&data=" . base64_encode($code));
        //选择支付页面
        switch($this->config['paytype']){
            //支付宝扫码
            case 3:
            case 4:
            case 17:
            case 18:
                if(isMobile()){
                    header("location: {$code}"); exit;
                    //$this->display("WeiXin/alipaywap");
                }else{
                    $this->display("WeiXin/alipay");
                }
                break;
            default:
                $this->display("WeiXin/Pay");//收银台
        }

    }

    /**
     * 验签
     *
     * @author AnLin
     * @version V1.0.0
     * @since 2018/6/4
     */
    private function sign($dataArr)
    {
        ksort($dataArr);
        $str = '';
        foreach ($dataArr as $key => $value) {
            if(!empty($value)) $str.=$key.'='.$value.'&';
        }
        $str = rtrim($str,'&'). $this->config['signkey'];

        return strtoupper(md5($str));
    }



    //通知
    public function notifyurl(){
       // $this->debug_callback();

        //IP白名单
        if(!$this->checkip(getIP(),['47.52.237.148'])){
            exit("wrong");
        }

        $p = json_decode(file_get_contents('php://input', 'r'),true);

        if(!$p || empty($p)){
            exit("wrong");
        }

        //获取订单信息
        $orderid = $p['outOrderId'];

        //获取订单
        $find = $this->checkOrderNotify($orderid);
        if(!$find){
            echo 'order_not_found'; exit;
        }

        //保存回调数据
        M("Order")->where(array("pay_orderid"=>$orderid))->save(array(
             "pay_orderid_rd"=>htmlspecialchars($p['tradeOrderCode'])
        ));


        $real_amount =  $p['amount'];     //实际支付金额
        $pay_amount =  $find['pay_amount']; //商户提交订单金额

        if(abs($real_amount - $pay_amount) > 1){
            echo 'wrong_money'; exit;
        }

        //获取渠道信息
        $this->config = Channel::getInstance()->find(['code'=>$this->class]);

        $sign = $p['sign'];
        unset($p['sign']);
        unset($p['returnParam']);

        $sign2 = $this->sign($p) ;

        if($sign !== $sign2){
            exit("sign_wrong");
        }

        if($p['partnerOrderStatus'] !== 'SUCCESS'){
            exit("sign_wrong");
        }


        $this->async($find['pay_orderid'],"SUCCESS");
    }

    public function callBackUrl(){

        echo '处理成功'; exit;
    }
}
